<template>
  <div class="app-container">
    <SearchForm
      v-show="showSearch"
      v-model="queryParams"
      :options="options.formOps"
      @onQuery="getList"
    >
    </SearchForm>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['preventionContingencyDispose:create']"
          >新增</el-button
        >
      </el-col>

      <!-- <el-col :span="1.5">
        <ImportExcel
          type="primary"
          :url="APIS.url"
          plain
          icon="Plus"
          @success="getList"
        ></ImportExcel>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <ExportExcel type="primary" :url="APIS.url" plain></ExportExcel>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <Table
      ref="table"
      :auto-featch="true"
      :fetch-data="fetchData"
      :options="options.table"
      @selectionChange="selectionChange"
      action-width="200"
    >
      <template #person="{ row }">
        {{ row.personName }}
      </template>

      <template #actionButton="{ row }">
        <el-button
          type="text"
          icon="Edit"
          @click="handleEdit(row)"
          v-hasPermi="['preventionContingencyDispose:update']"
          >修改
        </el-button>

        <el-button
          type="text"
          icon="Delete"
          style="color: red"
          @click="handleDel(row)"
          v-hasPermi="['preventionContingencyDispose:delete']"
          >删除
        </el-button>
        <el-button type="text" @click="handleExportPdf(row)"
          >导出pdf
        </el-button>
      </template>
    </Table>
    <DialogVform
      :formJson="formJson"
      ref="dialogVform"
      @onSubmit="onSubmit"
      :slots="['person', 'safetyLeader', 'jobName', 'fileSlot']"
    >
      <template #fileSlot>
        <el-form-item label="文件上传" prop="fileId">
          <FileUpload :limit="1" :fileSize="30" v-model="files"></FileUpload>
        </el-form-item>
      </template>
      <template v-for="item in slots" #[item.key]>
        <el-form-item
          :label="item.name"
          :prop="item.key"
          label-position="right"
        >
          <el-input
            v-model="form[item.key + 'Name']"
            readonly
            @click="onInnerOpen(item.key)"
          >
          </el-input>
        </el-form-item>
      </template>
      <template #jobName>
        <el-form-item label="岗位名称" prop="item.key" label-position="right">
          <el-select v-model="form.jobName" placeholder="" style="width: 100%">
            <el-option
              v-for="ele in postList"
              :key="ele.postName"
              :value="ele.postName"
              :label="ele.postName"
            ></el-option>
          </el-select>
        </el-form-item>
      </template>
      <TableSelect
        ref="userTableSelect"
        :queryApi="listUser"
        :options="[]"
        :rowKey="'userId'"
        rowLabel="nickName"
        @onConfirm="onUserConfirm"
        rowLabelText="用户昵称"
      >
        <template #formSlot="{ handleQuery, filterForm }">
          <el-col :span="8">
            <el-form-item label="部门名称">
              <el-input
                size="small"
                @change="handleQuery"
                v-model="filterForm.deptName"
                clearable
                style="width: 100%"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户名称">
              <el-input
                size="small"
                @change="handleQuery"
                v-model="filterForm.userName"
                clearable
                style="width: 100%"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
        </template>
        <template #tableSlot>
          <el-table-column
            label="部门"
            align="center"
            key="deptName"
            prop="dept.deptName"
          />
          <el-table-column
            label="用户名称"
            align="center"
            key="userName"
            prop="userName"
          />
          <el-table-column
            label="用户昵称"
            align="center"
            key="nickName"
            prop="nickName"
          />
        </template>
      </TableSelect>
    </DialogVform>
  </div>
</template>

<script setup>
import Table from "@/components/Table/index.vue";
import SearchForm from "@/components/searchForm/index";
import DialogVform from "@/components/dialogVform/index";
import { apis as APIS } from "@/api/hdanger/sanka/yjczk.js";
import formJson from "./components/options.json";
import { useAsyncData, useFormJsonNew } from "@/views/hooks/useAsyncData.js";
import { listUser } from "@/api/system/user";
import TableSelect from "@/components/tableSelect/index";
import { listPost } from "@/api/system/post";
import FileUpload from "@/components/FileUpload";
const files = ref([]);
const slots = ref([
  {
    name: "责任人",
    key: "person",
  },
]);
const { proxy } = getCurrentInstance();
const ops = useFormJsonNew(formJson, {
  sort: [],
  sortable: [],
});
const options = reactive({
  table: ops,
  formOps: ops.filter((i) =>
    ["affiliatedUnit", "jobName", "safetyJobName"].includes(i.prop)
  ),
});
const showSearch = ref(true);
const dialogVform = ref();
const table = ref();
watch(
  () => files,
  (newData) => {
    if (newData.value.length === 0) {
      form.value.fileName = "";
      form.value.fileId = "";
      form.value.fileUrl = "";
    } else {
      form.value.fileName = newData.value[0].name;
      form.value.fileId = newData.value[0].id;
      form.value.fileUrl = newData.value[0].url;
    }
  },
  {
    deep: true,
  }
);
const plugAdd = () => {
  files.value = [];
};
const plugEdit = (row) => {
  if (row.fileId) {
    files.value = [
      {
        name: row.fileName,
        id: row.fileId,
        url: row.fileUrl,
      },
    ];
  } else {
    files.value = [];
  }
  form.value.personId = row.personId;
  form.value.personName = row.personName;
  form.value.jobName = row.jobName;
};

const {
  onSubmit,
  fetchData,
  handleAdd,
  handleEdit,
  getList,
  handleDel,
  queryParams,
  form,
} = useAsyncData({
  APIS,
  formJson,
  dialogVform,
  table,
  proxy,
  plugEdit,
  plugAdd,
});
const handleExportPdf = (row) => {
  APIS.exportPdf(row.id, row.jobName + "应急处置卡");
};
const userType = ref("");
const userTableSelect = ref();
const onInnerOpen = (type) => {
  userType.value = type;
  let values =
    (form.value[type + "Id"] && (form.value[type + "Id"] + "").split(",")) ||
    [];
  let names =
    (form.value[type + "Name"] && form.value[type + "Name"].split(",")) || [];
  userTableSelect.value.open(
    values.map((item, index) => ({
      value: values[index],
      label: names[index],
    }))
  );
};
const onUserConfirm = (data) => {
  const values = data.map((item) => item.value);
  const names = data.map((item) => item.label);
  form.value[userType.value + "Name"] = names.join(",");
  form.value[userType.value + "Id"] = values.join(",");
};

const selectList = ref([]);
const selectionChange = (rows) => {
  selectList.value = rows;
};
const handleExport = () => {
  proxy.download2(
    "/preventionContingencyDispose/exportData",
    selectList.value.map((item) => item.id),
    `应急处置卡${new Date().getTime()}.xlsx`
  );
};
const postList = ref([]);
function getSsdyOptions() {
  listPost().then((res) => {
    postList.value = res.rows;
  });
}
getSsdyOptions();
</script>

<style lang="scss" scoped></style>
